package com.jnevision.dept.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jnevision.dept.mapper.DeptMapper;
import com.jnevision.dept.model.Dept;
import com.jnevision.user.model.User;
import com.jnevision.util.JsonMapper;

/**
 * <p>
 * 部门 服务实现类
 * </p>
 *
 * @author gavin
 * @since 2019-07-13
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> {
    @Autowired
    private StringRedisTemplate redisTemplate;

    private List<Dept> childrenList = new ArrayList<>();

    private void loopChildren(int id) {
        List<Dept> children = this.baseMapper.selectList(new QueryWrapper<Dept>().eq("parent_id", id).ne("type", 4));

        if (!CollectionUtils.isEmpty(children)) {
            this.childrenList.addAll(children);
            for (Dept dept : children) {
                this.loopChildren(dept.getId());
            }
        }
    }

    public List<Dept> getChildren(int id) {
        this.childrenList.clear();
        this.childrenList.add(this.getById(id)); // 放入本身部门

        this.loopChildren(id); // 放入所管辖的部门
        return this.childrenList;
    }

    /**
     * 获取部门所属的项目部
     * 
     * @param deptId
     * @return
     */
    public Dept getProject(int deptId) {
        Dept dept = this.baseMapper.selectById(deptId);

        if (!Objects.isNull(dept)) {
            if (dept.getType() == 2) {
                return dept;
            } else {
                return this.getProject(dept.getParentId());
            }
        }

        return dept;
    }

    public Dept getProject(String token) {
        User user = JsonMapper.nonDefaultMapper().fromJson(this.redisTemplate.boundValueOps(token).get(), User.class);
        Dept dept = this.getProject(user.getDeptId());
        return dept;
    }
}
